const path = require('path')

const express = require('express')
const multer = require('multer')
const app = express()
const port = 3001
const fs = require('fs')
const cors = require('cors')
const routes = require("./router/routes");
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// 引入http创建服务器实例的方法
const {createServer} = require('http')
const {Server} = require('socket.io')
// 创建http服务器实例
const httpServer = createServer(app)
// 创建socket.io的实例
const io = new Server(httpServer,{
  // 处理cors,解决跨域问题
  // path:'http://127.0.0.1:3002/path',
  cors:{
    origin: "*",//需要跨域资源共享的地址
    // origin: "http://localhost:5001",//需要跨域资源共享的地址
    allowedHeaders: ["my-custom-header"],
    credentials: true
  }
})

// 监听客户端连接，回调函数会传递本次连接的socket
io.on('connection',(socket) => {

  console.log(socket.id)
  // 监听到客户端发送的消息
  socket.on('sendToServer',(message) => {
    console.log(message)
    // 向客户端发送消息
    socket.emit('sendToClient',{
      message:'你好我是服务端'
    })
  })
  socket.on('disconnect', () => {
    console.log('中断连接');
  });
})

const storage = multer.diskStorage({
  destination:(req,file,cb) =>{
    cb(null, './uploads/')
  },
  filename: (req, file, cb) =>{
    cb(null, Date.now() + path.extname(file.originalname))
  }
})
//文件上传解析
const upload = multer({
  storage
})
// app.use(upload.any())

// upload.single('file'),//单个上传,file为字段名
// upload.any() //任意
// upload.array('file') // //多个上传

//用户模块,路由整体封装
routes.forEach((router) => {
  app.use("/", router);
});

app.post('/upload', upload.single('file'),(req,res,next)=>{
  console.log(req.files,444);
  res.end('文件上传成功')
})
//用户模块,路由单独封装
// const user = require('./router/admin/user')
// app.use('/user', user);
//商品模块
// const goods = require('./router/admin/goods')
// app.use('/goods', goods);
//app模块,路由封装
// const home = require('./router/app/home')
// app.use('/app', home);
app.use('/test',(req,res,next)=>{
  console.log('测试111');
  next()
},(req,res,next)=>{
  console.log('测试222');
})


app.listen(port, () => console.log(`应用启动,监听端口${port}!`))
httpServer.listen(3002,() =>{
  console.log('server is running at http://127.0.0.1:3002')
})